<?php

namespace App\Models\Sample;

use App\Helpers\Code;
use App\Models\Account\UserGroupMapUser;
use App\Models\BaseModel;
use App\Models\Basic\DictionaryMember;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use DB;

class SampleInoutRecord extends BaseModel
{

    protected $table = 'sample_inout_records';
    protected $fillable = [
        'code', 'description', 'state', 'type', 'entered_by', 'enter_date', 'checked_group', 'checked_by', 'submitted_by', 'submit_time', 'inout_date', 'express_company', 'express_number', 'project', 'salesman', 'created_by', 'updated_by', 'data_scope',
    ];
    public $sorter = [];
    public $params = ['code'];

    public function createdBy()
    {
        return $this->belongsTo('App\Models\Account\User', 'created_by');
    }

    public function updatedBy()
    {
        return $this->belongsTo('App\Models\Account\User', 'updated_by');
    }

    public function enteredBy()
    {
        return $this->belongsTo('App\Models\Account\User', 'entered_by');
    }

    public function checkedGroup()
    {
        return $this->belongsTo('App\Models\Account\UserGroup', 'checked_group');
    }

    public function checkedBy()
    {
        return $this->belongsTo('App\Models\Account\User', 'checked_by');
    }

    public function submittedBy()
    {
        return $this->belongsTo('App\Models\Account\User', 'submitted_by');
    }

    public function expressCompany()
    {
        return $this->belongsTo('App\Models\Basic\DictionaryMember', 'express_company', 'code');
    }

    public function salesman()
    {
        return $this->belongsTo('App\Models\Account\User', 'salesman');
    }

    //合同暂时没有
    /*public function project()
    {
        return $this->belongsTo('App\Models\Basic\DictionaryMember', 'express_company','code');
    }*/

    public function addOutForm($data)
    {
        $checkedBy = UserGroupMapUser::where(['group_id' => $data['checked_group'], 'user_id' => $data['checked_by']]);
        if (!$checkedBy) {
            return null;
        }

        if (isset($data['express_company']) && !empty($data['express_company'])) {
            $expressCompany = DictionaryMember::find($data['express_company']);
            if (!$expressCompany) {
                return Code::INSIDE_ERROR;
            }
            $data['express_company'] = $expressCompany->code;
        }

        //合同暂时没有,先不校验
        /*if(isset($data['project']) && !empty($data['project'])){
            $project = Project::find($data['express_company']);
            if(!$project){
                return Code::INSIDE_ERROR;
            }
            $data['project'] = $project->code;
        }*/

        if (isset($data['salesman']) && !empty($data['salesman'])) {
            $salesman = Project::find($data['salesman']);
            if (!$salesman) {
                return Code::INSIDE_ERROR;
            }
        }

        $date = substr(date('Ymd'), 2);
        $code = 'NOKXJY' . $date;
        $outForm = $this->where('code', 'like', '%' . $code . '%')->orderBy('id', 'desc')->first();
        if ($outForm) {
            $num = substr($outForm->code, 12) + 1;
            $length = strlen($num);
            if ($length == 1) {
                $outFormCode = $code . '000' . $num;
            } else if ($length == 2) {
                $outFormCode = $code . '00' . $num;
            } else if ($length == 3) {
                $outFormCode = $code . '0' . $num;
            } else {
                $outFormCode = $code . $num;
            }
        } else {
            $outFormCode = $code . '0001';
        }

        $userId = Auth::id();
        $data['created_by'] = $userId;
        $data['updated_by'] = $userId;
        $data['entered_by'] = $userId;
        $data['state'] = 0;
        $data['type'] = 0;
        $data['code'] = $outFormCode;
        $data['data_scope'] = $this->getDataScope();

        return $this->create($data);


        /*DB::beginTransaction();
        $model = $this->create($data);

        $insertData = [];
        foreach ($detailArr as $key => $val) {
            $data = [];
            $sample = Sample::find($val);
            if ($sample) {
                $detail = SampleInoutRecordDetail::where(['sample_inout_record_id' => $model->id, 'sample_id' => $val])->first();
                if ($detail) {
                    DB::rollBack();
                    return Code::INSIDE_ERROR_2;
                }
                $data['sample_inout_record_id'] = $model->id;
                $data['sample_id'] = $val;
                $data['data_scope'] = $model->data_scope;
                $data['created_at'] = new Carbon();
                $data['updated_at'] = new Carbon();
                $insertData[] = $data;
            } else {
                DB::rollBack();
                return Code::INSIDE_ERROR_1;
            }
        }

        SampleInoutRecordDetail::insert($insertData);
        DB::commit();
        return $model;*/
    }

    /*编辑发送单*/
    public function editOutForm($data, $detailArr, $id)
    {
        $model = $this->find($id);
        if (!$model) {
            return null;
        }

        $checkedBy = UserGroupMapUser::where(['group_id' => $data['checked_group'], 'user_id' => $data['checked_by']]);
        if (!$checkedBy) {
            return Code::INSIDE_ERROR;
        }

        if (isset($data['express_company']) && !empty($data['express_company'])) {
            $expressCompany = DictionaryMember::find($data['express_company']);
            if (!$expressCompany) {
                return Code::INSIDE_ERROR_1;
            }
            $data['express_company'] = $expressCompany->code;
        }

        //合同暂时没有,先不校验
        /*if(isset($data['project']) && !empty($data['project'])){
            $project = Project::find($data['express_company']);
            if(!$project){
                return Code::INSIDE_ERROR_1;
            }
            $data['project'] = $project->code;
        }*/

        if (isset($data['salesman']) && !empty($data['salesman'])) {
            $salesman = Project::find($data['salesman']);
            if (!$salesman) {
                return Code::INSIDE_ERROR_1;
            }
        }

        $data['updated_by'] = Auth::id();
        return $model->updateOrCreate($data);
    }

    /*获取指定发送单*/
    public function getOutForm($id)
    {
        $model = $this->with(['createdBy:id,username', 'updatedBy:id,username', 'enteredBy:id,username', 'checkedGroup:id,title', 'checkedBy:id,username', 'submittedBy:id,username', 'expressCompany:code,title', 'salesman:id,username'])
            ->where(['id' => $id, 'type' => 0])
            ->select(['id', 'code', 'description', 'state', 'type', 'entered_by', 'enter_date', 'checked_group', 'checked_by', 'submitted_by', 'submit_time', 'inout_date', 'express_company', 'express_number', 'project', 'salesman', 'created_by', 'updated_by', 'created_at', 'updated_at'])
            ->first();

        if (!$model) {
            return null;
        }

        return $model;
    }

    public function getOutFormList($limit, $sorter, $search, $defaultSorter)
    {
        $perPage = $limit > 0 ? $limit : $this->limit;
        if ($defaultSorter == 'desc') {
            $model = $this->orderBy('created_at', $defaultSorter);
        } else {
            $model = $this->orderBy($sorter[0], $sorter[1]);
        }

        $model->with(['createdBy:id,username', 'updatedBy:id,username', 'enteredBy:id,username', 'checkedGroup:id,title', 'checkedBy:id,username', 'submittedBy:id,username', 'expressCompany:code,title', 'salesman:id,username'])
            ->where(['type' => 0])
            ->select(['id', 'code', 'description', 'state', 'type', 'entered_by', 'enter_date', 'checked_group', 'checked_by', 'submitted_by', 'submit_time',
                'inout_date', 'express_company', 'express_number', 'project', 'salesman', 'created_by', 'updated_by', 'created_at', 'updated_at']);

        foreach ($search as $key => $value) {
            switch ($key) {
                case 'code':
                    $model->where($key, 'like', '%' . $value . '%');
                    break;
            }
        }

        return $model->paginate($perPage)->toArray();
    }

    /*发送单提交审核*/
    public function submitOutForm($id)
    {
        $model = $this->where(['id' => $id, 'state' => 0, 'type' => 0])->first();
        if (!$model) {
            return null;
        }

        $model->state = 1;
        $model->submitted_by = Auth::id();
        $model->submit_time = new Carbon();
        $model->save();
        return true;
    }

    /*发送单审核通过*/
    public function approveOutForm($data, $id)
    {
        $model = $this->where(['id' => $id, 'state' => 1])->first();
        if (!$model) {
            return null;
        }

        $model->state = $data['state'];
        $model->checked_by = Auth::id();
        $model->save();
        return true;
    }

    /*添加接收单*/
    public function addInForm($data, $detailArr)
    {
        $checkedBy = UserGroupMapUser::where(['group_id' => $data['checked_group'], 'user_id' => $data['checked_by']]);
        if (!$checkedBy) {
            return null;
        }

        $date = substr(date('Ymd'), 2);
        $code = 'NIKXJY' . $date;
        $outForm = $this->where('code', 'like', '%' . $code . '%')->orderBy('id', 'desc')->first();
        if ($outForm) {
            $num = substr($outForm->code, 12) + 1;
            $length = strlen($num);
            if ($length == 1) {
                $outFormCode = $code . '000' . $num;
            } else if ($length == 2) {
                $outFormCode = $code . '00' . $num;
            } else if ($length == 3) {
                $outFormCode = $code . '0' . $num;
            } else {
                $outFormCode = $code . $num;
            }
        } else {
            $outFormCode = $code . '0001';
        }

        $userId = Auth::id();
        $data['created_by'] = $userId;
        $data['updated_by'] = $userId;
        $data['entered_by'] = $userId;
        $data['state'] = 0;
        $data['type'] = 1;
        $data['code'] = $outFormCode;
        $data['data_scope'] = $this->getDataScope();

        DB::beginTransaction();
        $model = $this->create($data);

        $insertData = [];
        foreach ($detailArr as $key => $val) {
            $data = [];
            $sample = Sample::where('bar_code', $val)->first();
            if ($sample) {
                $detail = SampleInoutRecordDetail::where(['sample_inout_record_id' => $model->id, 'sample_id' => $val])->first();
                if ($detail) {
                    DB::rollBack();
                    return Code::INSIDE_ERROR_2;
                }
                $data['sample_inout_record_id'] = $model->id;
                $data['sample_id'] = $sample->id;
                $data['data_scope'] = $model->data_scope;
                $data['created_at'] = new Carbon();
                $data['updated_at'] = new Carbon();
                $insertData[] = $data;
            } else {
                DB::rollBack();
                return Code::INSIDE_ERROR_1;
            }
        }

        SampleInoutRecordDetail::insert($insertData);
        DB::commit();
        return $model;
    }

    /*编辑接收单*/
    public function editInForm($data, $detailArr, $id)
    {
        $model = $this->where(['type' => 1, 'id' => $id])->first();
        if (!$model) {
            return null;
        }

        $checkedBy = UserGroupMapUser::where(['group_id' => $data['checked_group'], 'user_id' => $data['checked_by']]);
        if (!$checkedBy) {
            return Code::INSIDE_ERROR;
        }

        DB::beginTransaction();
        $data['updated_by'] = Auth::id();
        $model->updateOrCreate($data);

        $details = SampleInoutRecordDetail::where('sample_inout_record_id', $id)->get(['id'])->toArray();
        $oldDetailIdArr = array_values(array_column($details,'id'));

        $insertData = [];
        $newDetailIdArr = [];
        foreach ($detailArr as $key => $val) {
            $data = [];
            $sample = Sample::where('bar_code', $val)->first();
            if ($sample) {
                $detail = SampleInoutRecordDetail::where(['sample_inout_record_id' => $id, 'sample_id' => $sample->id])->first();
                if ($detail) {
                    $newDetailIdArr[] = $detail->id;
                } else {
                    $data['sample_inout_record_id'] = $model->id;
                    $data['sample_id'] = $sample->id;
                    $data['data_scope'] = $model->data_scope;
                    $data['created_at'] = new Carbon();
                    $data['updated_at'] = new Carbon();
                    $insertData[] = $data;
                }
            } else {
                DB::rollBack();
                return Code::INSIDE_ERROR_1;
            }
        }

        if (count($insertData) > 0) {
            SampleInoutRecordDetail::insert($insertData);
        }

        $deleteIdArr = array_diff($oldDetailIdArr, $newDetailIdArr);
        if (count($deleteIdArr) > 0) {
            SampleInoutRecordDetail::whereIn('id', $deleteIdArr)->delete();
        }

        DB::commit();
        return $model;
    }

    /*接收单提交审核*/
    public function submitInForm($id)
    {
        $model = $this->where(['id' => $id, 'state' => 0, 'type' => 1])->first();
        if (!$model) {
            return null;
        }

        $model->state = 1;
        $model->submitted_by = Auth::id();
        $model->submit_time = new Carbon();
        $model->save();
        return true;
    }

    /*接收单审核通过*/
    public function approveInForm($data, $id)
    {
        $model = $this->where(['id' => $id, 'state' => 1, 'type' => 1])->first();
        if (!$model) {
            return null;
        }

        $model->state = $data['state'];
        $model->checked_by = Auth::id();
        $model->save();
        return true;
    }

    /*获取指定接收单*/
    public function getInForm($id)
    {
        $model = $this->with(['createdBy:id,username', 'updatedBy:id,username', 'enteredBy:id,username', 'checkedGroup:id,title', 'checkedBy:id,username', 'submittedBy:id,username'])
            ->where(['type' => 1, 'id' => $id])
            ->select(['id', 'code', 'description', 'state', 'type', 'entered_by', 'enter_date', 'checked_group', 'checked_by', 'submitted_by', 'submit_time',
                'inout_date', 'created_by', 'updated_by', 'created_at', 'updated_at'])
            ->first();
        if(!$model){
            return null;
        }

        return $model;
    }

    /*获取接收单列表*/
    public function getInFormList($limit, $sorter, $search, $defaultSorter)
    {
        $perPage = $limit > 0 ? $limit : $this->limit;
        if ($defaultSorter == 'desc') {
            $model = $this->orderBy('created_at', $defaultSorter);
        } else {
            $model = $this->orderBy($sorter[0], $sorter[1]);
        }

        $model->with(['createdBy:id,username', 'updatedBy:id,username', 'enteredBy:id,username', 'checkedGroup:id,title', 'checkedBy:id,username', 'submittedBy:id,username'])
            ->where(['type' => 1])
            ->select(['id', 'code', 'description', 'state', 'type', 'entered_by', 'enter_date', 'checked_group', 'checked_by', 'submitted_by', 'submit_time',
                'inout_date', 'created_by', 'updated_by', 'created_at', 'updated_at']);

        foreach ($search as $key => $value) {
            switch ($key) {
                case 'code':
                    $model->where($key, 'like', '%' . $value . '%');
                    break;
            }
        }

        return $model->paginate($perPage)->toArray();
    }
}
